<template>
  <div class="page-container">
    <!-- 顶部导航 -->
    <div class="header">
      <button @click="$router.go(-1)" class="back-btn">
        <svg class="back-icon" viewBox="0 0 24 24" width="24" height="24">
          <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
      </button>
      <h1>疾病类别</h1>
    </div>

    <div ref="container" class="model-container"></div>
    
    <!-- 修改disease-panel，添加关闭按钮 -->
    <div v-if="selectedPart" class="disease-panel">
      <div class="panel-header">
        <h3>{{ selectedPart.name }}</h3>
        <button @click="closePanel" class="close-btn">×</button>
      </div>
      <div class="disease-list">
        <div v-for="disease in selectedPart.diseases" :key="disease.name" class="disease-item">
          <h4>{{ disease.name }}</h4>
          <p>{{ disease.description }}</p>
          <div class="solution" v-if="disease.solution">
            <strong>解决方案:</strong> {{ disease.solution }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import * as TWEEN from '@tweenjs/tween.js';
import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const container = ref(null);
    const selectedPart = ref(null);
    
    // 添加关闭面板方法
    const closePanel = () => {
      selectedPart.value = null;
      // 重置模型高亮
      if (model) {
        model.traverse((child) => {
          if (child.isMesh) {
            child.material.color.copy(child.userData.originalMaterial.color);
          }
        });
      }
    };

    // 人体部位数据
    const bodyParts = [
      {
        name: '头部',
        meshName: 'Beta_Surface',
        position: { x: 0, y: 1.4, z: 0 },
        yRange: { min: 1.2, max: 2.0 },
        xRange: { min: -0.2, max: 0.2 },
        diseases: [
          { name: '偏头痛', description: '反复发作的搏动性头痛，常伴随恶心、呕吐' },
          { name: '紧张性头痛', description: '头部持续钝痛，有压迫感或紧束感' },
          { name: '眩晕症', description: '头晕目眩，天旋地转，伴有恶心' },
          { name: '三叉神经痛', description: '面部剧烈疼痛，如触电般' },
          { name: '鼻窦炎', description: '鼻塞、头痛、面部压痛' }
        ]
      },
      {
        name: '左手',
        meshName: 'Beta_Surface',
        position: { x: -0.8, y: 0.6, z: 0 },
        yRange: { min: 0.7, max: 1.0 },
        xRange: { min: -1.6, max: -1.2 },
        diseases: [
          { name: '腕管综合征', description: '手腕疼痛、麻木，特别是夜间加重' },
          { name: '关节炎', description: '关节疼痛、肿胀、活动受限' },
          { name: '肌腱炎', description: '手腕活动时疼痛，可能伴有肿胀' },
          { name: '类风湿性关节炎', description: '多个手指关节疼痛和变形' },
          { name: '振动病', description: '手指发麻、刺痛，对冷敏感' }
        ]
      },
      {
        name: '右手',
        meshName: 'Beta_Surface',
        position: { x: 0.8, y: 0.6, z: 0 },
        yRange: { min: 0.7, max: 1.0 },
        xRange: { min: 1.2, max: 1.6 },
        diseases: [
          { name: '腕管综合征', description: '手腕疼痛、麻木，特别是夜间加重' },
          { name: '关节炎', description: '关节疼痛、肿胀、活动受限' },
          { name: '肌腱炎', description: '手腕活动时疼痛，可能伴有肿胀' },
          { name: '类风湿性关节炎', description: '多个手指关节疼痛和变形' },
          { name: '振动病', description: '手指发麻、刺痛，对冷敏感' }
        ]
      },
      {
        name: '左臂',
        meshName: 'Beta_Surface',
        position: { x: -0.5, y: 0.9, z: 0 },
        yRange: { min: 0.8, max: 1.2 },
        xRange: { min: -1.0, max: -0.3 },
        diseases: [
          { name: '肱骨外侧炎', description: '手肘外侧疼痛，握力减弱' },
          { name: '肱二头肌腱炎', description: '上臂前侧疼痛，弯曲手臂时加重' },
          { name: '滑囊炎', description: '肘部肿胀、疼痛、压痛' },
          { name: '神经卡压', description: '手臂麻木、刺痛、无力' },
          { name: '肌肉拉伤', description: '突发性疼痛，活动受限' }
        ]
      },
      {
        name: '右臂',
        meshName: 'Beta_Surface',
        position: { x: 0.5, y: 0.9, z: 0 },
        yRange: { min: 0.8, max: 1.2 },
        xRange: { min: 0.3, max: 1.0 },
        diseases: [
          { name: '肱骨外侧炎', description: '手肘外侧疼痛，握力减弱' },
          { name: '肱二头肌腱炎', description: '上臂前侧疼痛，弯曲手臂时加重' },
          { name: '滑囊炎', description: '肘部肿胀、疼痛、压痛' },
          { name: '神经卡压', description: '手臂麻木、刺痛、无力' },
          { name: '肌肉拉伤', description: '突发性疼痛，活动受限' }
        ]
      },
      {
        name: '胸部',
        meshName: 'Beta_Surface',
        position: { x: 0, y: 0.8, z: 0 },
        yRange: { min: 0.6, max: 1.2 },
        xRange: { min: -0.3, max: 0.3 },
        diseases: [
          { name: '胸闷', description: '呼吸不畅，胸部压迫感' },
          { name: '胸肌拉伤', description: '胸部肌肉疼痛，活动时加重' },
          { name: '肋间神经痛', description: '胸壁刺痛，呼吸时加重' },
          { name: '胸骨压痛', description: '胸骨部位疼痛，触压时明显' },
          { name: '胸壁炎', description: '胸痛，深呼吸或咳嗽时加重' }
        ]
      },
      {
        name: '腹部',
        meshName: 'Beta_Surface',
        position: { x: 0, y: 0.3, z: 0 },
        yRange: { min: 0, max: 0.6 },
        xRange: { min: -0.3, max: 0.3 },
        diseases: [
          { name: '消化不良', description: '上腹部不适，胀气，食欲不振' },
          { name: '胃炎', description: '上腹痛、烧心、反酸' },
          { name: '结肠炎', description: '腹痛、腹泻、粘液便' },
          { name: '胆囊炎', description: '右上腹痛，恶心呕吐' },
          { name: '腹肌拉伤', description: '腹部肌肉疼痛，活动时加重' }
        ]
      },
      {
        name: '左脚',
        meshName: 'Beta_Surface',
        position: { x: -0.15, y: -0.9, z: 0 },
        yRange: { min: -2.0, max: -0.8 },
        xRange: { min: -0.5, max: -0.1 },
        diseases: [
          { name: '足底筋膜炎', description: '足跟疼痛，尤其是早晨起床时' },
          { name: '跖骨痛', description: '前脚掌疼痛，行走时加重' },
          { name: '踝关节扭伤', description: '踝部疼痛、肿胀、活动受限' },
          { name: '足拇外翻', description: '大脚趾向外偏移，关节肿胀' },
          { name: '跟腱炎', description: '脚后跟疼痛，走路时加重' }
        ]
      },
      {
        name: '右脚',
        meshName: 'Beta_Surface',
        position: { x: 0.15, y: -0.9, z: 0 },
        yRange: { min: -2.0, max: -0.8 },
        xRange: { min: 0.1, max: 0.5 },
        diseases: [
          { name: '足底筋膜炎', description: '足跟疼痛，尤其是早晨起床时' },
          { name: '跖骨痛', description: '前脚掌疼痛，行走时加重' },
          { name: '踝关节扭伤', description: '踝部疼痛、肿胀、活动受限' },
          { name: '足拇外翻', description: '大脚趾向外偏移，关节肿胀' },
          { name: '跟腱炎', description: '脚后跟疼痛，走路时加重' }
        ]
      },
      {
        name: '腿部',
        meshName: 'Beta_Surface',
        position: { x: 0, y: -0.5, z: 0 },
        yRange: { min: -0.8, max: 0 },
        xRange: { min: -0.3, max: 0.3 },
        diseases: [
          { name: '肌肉酸痛', description: '运动后肌肉疼痛，行走不适' },
          { name: '小腿抽筋', description: '突发性剧烈疼痛，肌肉僵硬' },
          { name: '膝关节炎', description: '膝关节疼痛、肿胀、活动受限' },
          { name: '静脉曲张', description: '腿部静脉凸起、疼痛' },
          { name: '腘窝囊肿', description: '膝关节后方肿块，屈伸时不适' }
        ]
      }
    ];

    // 初始化3D场景
    let scene, camera, renderer, controls, model;
    let currentHighlight = null; // 添加当前高亮状态跟踪
    
    const initScene = () => {
      // 创建场景
      scene = new THREE.Scene();
      scene.background = new THREE.Color(0xf0f0f0);
      
      // 创建相机
      camera = new THREE.PerspectiveCamera(
        75,
        container.value.clientWidth / container.value.clientHeight,
        0.1,
        1000
      );
      camera.position.z = 5;
      
      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(container.value.clientWidth, container.value.clientHeight);
      renderer.setPixelRatio(window.devicePixelRatio);
      container.value.appendChild(renderer.domElement);
      
      // 添加光源
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
      scene.add(ambientLight);
      
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      directionalLight.position.set(1, 1, 1);
      scene.add(directionalLight);
      
      // 添加控制器
      controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.dampingFactor = 0.05;
      
      // 加载3D模型
      loadModel();
      
      // 添加窗口大小调整监听
      window.addEventListener('resize', onWindowResize);
      
      // 开始动画循环
      animate();
    };
    
    const loadModel = () => {
      const loader = new GLTFLoader();
      
      // 替换为你的模型路径
      loader.load(
        '/models/Xbot.glb',
        (gltf) => {
          model = gltf.scene;
          
          // 调整模型位置和大小
          model.position.set(0, -2, 0);
          model.scale.set(2, 2, 2);
          
          // 为每个部位设置交互属性
          setupModelInteractions(model);
          
          scene.add(model);
        },
        undefined,
        (error) => {
          console.error('Error loading model:', error);
        }
      );
    };
    
    const setupModelInteractions = (model) => {
      // 遍历模型找到各部位
      model.traverse((child) => {
        if (child.isMesh) {
          // 设置初始颜色
          child.material.color.setHex(0xffccaa);
          
          // 克隆原始材质用于悬停效果
          child.userData.originalMaterial = child.material.clone();
        }
      });
      
      // 添加点击事件监听
      container.value.addEventListener('click', onClick, false);
    };
    
    const onClick = (event) => {
      const mouse = new THREE.Vector2();
      const rect = event.target.getBoundingClientRect();
      mouse.x = ((event.clientX - rect.left) / container.value.clientWidth) * 2 - 1;
      mouse.y = -((event.clientY - rect.top) / container.value.clientHeight) * 2 + 1;
      
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(mouse, camera);
      
      const intersects = raycaster.intersectObject(model, true);
      
      if (intersects.length > 0) {
        const point = intersects[0].point;
        console.log('Click position:', point);
        
        // 打印每个部位的检测结果
        bodyParts.forEach(part => {
          const inYRange = point.y >= part.yRange.min && point.y <= part.yRange.max;
          const inXRange = point.x >= part.xRange.min && point.x <= part.xRange.max;
          console.log(`${part.name}: inYRange=${inYRange}, inXRange=${inXRange}, x=${point.x}, y=${point.y}`);
        });

        // 找到对应的身体部位
        const clickedPart = bodyParts.find(part => {
          const inYRange = point.y >= part.yRange.min && point.y <= part.yRange.max;
          const inXRange = point.x >= part.xRange.min && point.x <= part.xRange.max;
          return inYRange && inXRange;
        });
        
        console.log('Clicked part:', clickedPart?.name);
        
        if (clickedPart) {
          if (!currentHighlight || currentHighlight.name !== clickedPart.name) {
            if (currentHighlight) {
              model.traverse((child) => {
                if (child.isMesh) {
                  child.material.color.copy(child.userData.originalMaterial.color);
                }
              });
            }
            
            const clickedMesh = intersects[0].object;
            new TWEEN.Tween(clickedMesh.material.color)
              .to({ r: 1, g: 0.5, b: 0.5 }, 300)
              .start();
            
            currentHighlight = clickedPart;
            selectedPart.value = clickedPart;
          } else {
            model.traverse((child) => {
              if (child.isMesh) {
                child.material.color.copy(child.userData.originalMaterial.color);
              }
            });
            currentHighlight = null;
            selectedPart.value = null;
          }
        } else {
          if (currentHighlight) {
            model.traverse((child) => {
              if (child.isMesh) {
                child.material.color.copy(child.userData.originalMaterial.color);
              }
            });
            currentHighlight = null;
            selectedPart.value = null;
          }
        }
      }
    };
    
    const onWindowResize = () => {
      camera.aspect = container.value.clientWidth / container.value.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(container.value.clientWidth, container.value.clientHeight);
    };
    
    const animate = () => {
      requestAnimationFrame(animate);
      controls.update();
      TWEEN.update();
      renderer.render(scene, camera);
    };
    
    onMounted(() => {
      initScene();
    });
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', onWindowResize);
      container.value?.removeEventListener('click', onClick);
    });
    
    return {
      container,
      selectedPart,
      closePanel // 导出关闭方法
    };
  }
};
</script>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  padding: 8px;
  margin-right: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.back-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.back-btn:active {
  background-color: rgba(0, 0, 0, 0.1);
}

.back-icon {
  fill: #333;
  transition: transform 0.3s ease;
}

.back-btn:hover .back-icon {
  transform: translateX(-2px);
}

.back-btn:active .back-icon {
  transform: translateX(-4px);
}

.header h1 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.model-container {
  flex: 1;
  width: 100%;
  position: relative;
}

.disease-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-radius: 12px;
  max-width: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.05);
  color: #333;
}

.disease-list {
  max-height: 300px;
  overflow-y: auto;
}

.disease-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
}

.disease-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.disease-item h4 {
  margin: 0 0 5px 0;
  color: #d35400;
}

.disease-item p {
  margin: 0 0 8px 0;
  color: #555;
}

.solution {
  background: #f8f9fa;
  padding: 8px;
  border-radius: 4px;
  font-size: 0.9em;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .disease-panel {
    left: 10px;
    right: 10px;
    max-width: none;
    margin: 0 10px;
  }
}
</style>
